package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.bean.Employee;
import com.itheima.dao.EmployeeDao;
import com.itheima.exception.CustomException;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeDao, Employee> implements EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;

    @Override
    public void saveEmp(Employee employee) {
        //1.判断员工用户名是否存在，返回Employee对象
        //1.1：创建wrapper对象
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //1.2：设置查询条件
        wrapper.eq(Employee::getUsername,employee.getUsername());
        //1.3：调用查询方法 传入wrapper对象
        Employee emp = employeeDao.selectOne(wrapper);

        //2.存在：提示用户名已存在
        if(emp!=null){
            throw new CustomException(0,"用户名'"+employee.getUsername()+"'已存在！");
        }

        //3.不存在：将员工信息插入到数据库employee表中
        employeeDao.insert(employee);
    }

    @Override
    public Page<Employee> findPage(int page, int pageSize, String name) {
        //1.配置MyBatisPlus分页拦截器

        //2.执行分页查询 返回Page对象
        //2.1：将分页查询参数page和pageSize封装到Page对象中
        Page<Employee> employeePage = new Page<>(page, pageSize);

        //2.2：创建wrapper对象 设置查询条件
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!=null && name.length()>0,Employee::getName,name);

        //2.3：调用selectPage方法 传入Page和Wrapper对象 完成分页查询
        employeeDao.selectPage(employeePage,wrapper);

        //2.4：返回Page对象
        return employeePage;
    }

    @Override
    public int updateEmp(Employee employee) {
        //修改员工状态status  MyBatisPlus中的修改默认使用了动态修改部分字段  id和status，只会根据id修改status
        int rows = employeeDao.updateById(employee);

        return rows;
    }
}
